// Truncate long lines.
//
// trunc(1) truncates a line to no longer than the specified length. If the
//length is unspecified it defaults to 80 characters. If no terminator is
//specified, truncated lines will end abruptly; otherwise, the last characters
//of the truncated line will be replaces by the characters of the terminator.
//Characters are assumed to be UTF-8.
package main

import (
	"os"
	"log"
	"flag"
	"fmt"
	"utf8"
	"bufio"
)

var (
	max_length = flag.Int("c", 80, "Maximum characters in a line.")
	terminator = flag.String("t", "", "Truncated line terminator.")
)

func fatal(err ...interface{}) {
	flag.PrintDefaults()
	log.Fatalln(err...)
}

//BUG(jmf): tabs are counted as one character

func main() {
	log.SetFlags(0)
	flag.Parse()
	if flag.NArg() != 0 {
		fatal()
	}

	tlen := utf8.RuneCountInString(*terminator)
	if *max_length < tlen {
		fatal("Cannot truncate line less than length of terminator.")
	}

	in := bufio.NewReader(os.Stdin)
	end := *max_length - tlen
	for {
		line, err := in.ReadString('\n')

		if len(line) == 0 && err != nil {
			return
		}

		rline := utf8.NewString(line)
		if rline.RuneCount() <= *max_length {
			fmt.Print(line)
		} else {
			fmt.Print(rline.Slice(0, end), *terminator, "\n")
		}

		if err != nil {
			return
		}
	}
}
